package com.wzh.test;

import java.util.Scanner;

/**
 * 用数组模拟一个队列
 * 提供四个方法
 * isFull,isEmpty,add,get
 */
@SuppressWarnings(value = "all")
public class ArrayQueueDemo {
    public static void main(String[] args) {

        MyQueue myQueue = new MyQueue(3);
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;

        while (loop){
            System.out.println("请输入命令：add,head,show");
            String command = scanner.next();
            switch (command){
                case "add":
                    System.out.println("请输入要添加的element");
                    int element = scanner.nextInt();
                    try{
                        myQueue.add(element);
                    }catch (RuntimeException e){
                        System.out.println(e.getMessage());
                    }

                    break;
                case "head":
                    try{
                        int head = myQueue.head();
                        System.out.println(head);
                    }catch (RuntimeException e){
                        System.out.println(e.getMessage());
                    }

                    break;
                case "show":
                    myQueue.show();
                    break;
            }
        }
    }
}

/**
 * 队列：
 *  先进先出，从尾部add，从头部get
 */
@SuppressWarnings(value = "all")
class MyQueue{
    private int[] arr;
    private int first;//指向第一个有效元素的前一个位置
    private int last;//指向最后一个有效元素
    private int maxLength;//最大长度

    public MyQueue(int length){
        this.arr = new int[3];
        this.first = -1;
        this.last = -1;
        this.maxLength = length;
    }

    public boolean isEmpty(){
        return this.first == this.last;
    }

    public boolean isFull(){
        return this.last == this.maxLength - 1;
    }

    public void add(int element){
        if(isFull()){
            throw new RuntimeException("队列已满");
        }
        this.last++;
        this.arr[this.last] = element;
    }

    public int head(){
        if(isEmpty()){
            throw new RuntimeException("队列为空");
        }
        this.first++;
        return this.arr[this.first];
    }

    public void show(){
        if(isEmpty()){
            System.out.println("队列为空");
        }
        for(int i = this.first + 1;i <=this.last;i++){
            System.out.println(this.arr[i]);
        }
    }

}
